package org.file5.service.impl;

import java.io.IOException;

import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicException;
import net.sf.jmimemagic.MagicMatch;
import net.sf.jmimemagic.MagicMatchNotFoundException;
import net.sf.jmimemagic.MagicParseException;

import org.apache.log4j.Logger;
import org.file5.dao.DaoFascade;
import org.file5.domain.Attachment;
import org.file5.exception.ImageTooLargeException;
import org.file5.exception.InvalidSwagImageException;
import org.file5.exception.LoadImageFromURLException;
import org.file5.service.AttachmentService;
import org.file5.service.ImageService;
import org.file5.util.DataBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.appengine.api.datastore.Blob;

/**
 * Attachment Service
 * 
 * @author Conan Chan
 * 
 */
@Service("attachmentService")
public class AttachmentServiceImpl implements AttachmentService {

	private final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	DaoFascade df;
	
	@Autowired
	ImageService imageService;
	private Magic jmimeMagicParser = new Magic();

	public AttachmentServiceImpl() {
	}

	@Override
	public Attachment populateAttachmentImage(Attachment attachment)
			throws LoadImageFromURLException, ImageTooLargeException,
			InvalidSwagImageException, IOException {
		MultipartFile mpf = attachment.getMultipartFile();
		if (mpf != null && mpf.getSize() > 0 && mpf.getBytes() != null
				&& mpf.getBytes().length > 0) {

			imageService.checkImageMimeType(mpf.getBytes());
			// Resize the image before saving
			attachment.setFileContent(new Blob(mpf.getBytes()));
		}
		return attachment;
	}

	public byte[] getThumbnailBytes(String key,Integer width,Integer height) {
		Attachment image = df.getBaseDao().find(Attachment.class, key);
		if (image == null || image.getFileContent() == null) {
			return null;
		}
		return imageService.getResizedThumbnailImageBytes(width,height,image.getFileContent().getBytes());
	}

	@Override
	public Attachment update(Attachment attachment) {

		MultipartFile mpf = attachment.getMultipartFile();
		if(mpf!=null&&mpf.getSize()>0){
			try {
				MagicMatch match = jmimeMagicParser.getMagicMatch(mpf.getBytes());
				String mimeType = match.getMimeType();
				attachment.setFileContent(new Blob(mpf.getBytes()));
				attachment.setFileType(mimeType);
				String fileExt = "gif";
				int dotIdx = mpf.getOriginalFilename().lastIndexOf(".");				
				if(dotIdx>0){
					 fileExt = mpf.getOriginalFilename().substring(dotIdx+1);
				}
				attachment.setFileExt(fileExt);
			} catch (IOException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (MagicParseException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (MagicMatchNotFoundException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			} catch (MagicException e) {
				logger.error(e.getMessage());
				e.printStackTrace();
			}
		}			
		attachment = df.getBaseDao().addUpdate(attachment);
		return attachment;
	}

	@Override
	public DataBean<Attachment> getAttachments(int startPosition,
			int maxResult, Object... params) {		
		return df.getAttachmentDao().getAttachments(startPosition, maxResult, params);
	}


	@Override
	public void delete(String uid) {
		Attachment attachment = df.getBaseDao().find(Attachment.class, uid);
		if (attachment != null) {
			df.getBaseDao().remove(attachment);
		}

	}
}